package com.atguigu.eduservice.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.ExcelSubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    public EduSubjectService eduSubjectService;


    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }


    @Override
    public void invoke(ExcelSubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {

            throw new GuliException(20001, "文件数据为空");
        }
        //添加一级分类
        EduSubject oneSubject = this.eduOneSubject(subjectData.getOneSubjectName(), eduSubjectService);
        if (oneSubject == null) {//没有相同一级分类，进行添加

            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubjectName());//一级分类名称
            eduSubjectService.save(oneSubject);
        }
        //获取一级分类ID值
        String pid = oneSubject.getId();
        //添加二级分类
        EduSubject twoSubject = this.eduTwoSubject(subjectData.getTwoSubjectName(), eduSubjectService, pid);
        if (twoSubject == null) {//没有相同一级分类，进行添加

            twoSubject = new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectData.getTwoSubjectName());//一级分类名称
            eduSubjectService.save(twoSubject);
        }
    }

    //判断一级分类不能重复添加
    private EduSubject eduOneSubject(String name, EduSubjectService eduSubjectService) {

        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();

        wrapper.eq("title", name);
        wrapper.eq("parent_id", 0);

        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;
    }

    //判断二级分类不能重复添加
    private EduSubject eduTwoSubject(String name, EduSubjectService eduSubjectService, String pid) {

        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();

        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);

        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
